<template>
  <div class="app-container" style="height: 90%">
    <el-container style="border: 1px solid #eee">
      <el-aside
        width="250px"
        style="
          background-color: rgb(238, 241, 246);
          margin-bottom: 0;
          padding-bottom: 20px;
        "
      >
        <div style="padding-bottom:10px ;1">
          <el-row>
            <el-col :span="10" :offset="2"><strong>角色列表</strong></el-col>
          </el-row>
        </div>
        <el-menu default-active="0" @select="roleSelect">
          <template v-for="(role, index) in roles">
            <el-menu-item :key="index" :index="index + ''">
              <svg-icon icon-class="peoples" style="margin: 0; width: 18px" />
              <span>{{ role.name }}</span>
            </el-menu-item>
          </template>
        </el-menu>
      </el-aside>
      <el-table
        v-loading="listLoading"
        :data="tableMenus"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column :label="$t('rolePermission.menuName')" width="150px">
          <template slot-scope="{ row/*, $index */ }">
            <div
              :style="{ 'padding-left': row.parentId == 0 ? '0px' : '15px' }"
            >
              <el-checkbox
                v-model="checkedList[row.id + '']"
                :indeterminate="indeterminates[row.id + '']"
                size="large"
                style="margin-right: 5px"
                @change="checkChange(row.id)"
              />
              <i
                v-if="row.icon && row.icon.indexOf('el-icon') >= 0"
                :class="row.icon"
                style="margin: 0; width: 18px"
              />
              <svg-icon
                v-if="row.icon && row.icon.indexOf('el-icon') < 0"
                :icon-class="row.icon"
                style="margin: 0; width: 18px"
              />{{ row.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('rolePermission.elementName')">
          <template slot-scope="{ row/*, $index */ }">
            <el-checkbox
              v-for="(item, index) in list.filter(
                (x) => x.parentId == row.id && x.permissionType == 1
              )"
              :key="index"
              v-model="checkedList[row.id + '_1_' + item.id]"
              :label="item.name"
              size="large"
              border
              style="margin-right: 10px"
              @change="checkChange(row.id, 1, item.id)"
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('rolePermission.apiName')">
          <template slot-scope="{ row/*, $index */ }">
            <el-checkbox
              v-for="(item, index) in list.filter(
                (x) => x.parentId == row.id && x.permissionType == 2
              )"
              :key="index"
              v-model="checkedList[row.id + '_2_' + item.id]"
              :label="item.name"
              size="large"
              border
              style="margin-right: 10px"
              @change="checkChange(row.id, 2, item.id)"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-container>
    <div style="clear: both; text-align: center; padding-top: 20px">
      <el-button
        v-waves
        type="primary"
        size="large"
        @click="savePermissions"
      >保存</el-button>
    </div>
  </div>
</template>

<script>
import { getAllPermissions } from '@/api/permission'
import { getAllRoleList, getPermissions, savePermissions } from '@/api/role'
import waves from '@/directive/waves' // waves directive

export default {
  name: 'RolePermission',
  directives: { waves },
  data() {
    return {
      list: null,
      listLoading: true,
      tableMenus: [],
      roles: [],
      checkedList: {}
    }
  },
  created() {
    this.getPermissionList()
    this.getRoleList()
  },
  methods: {
    checkChange(rowId, type, childId) {
      const checkedList = this.checkedList
      const tableMenus = this.tableMenus
      if (!type) {
        const menu = tableMenus.find((x) => x.id === rowId)
        if (menu.parentId === 0) {
          // 同步子菜单的选择框的值
          const childs = tableMenus.filter((x) => x.parentId === rowId)
          for (const key in childs) {
            checkedList[childs[key].id + ''] = checkedList[rowId + '']
          }
          for (const key in childs) {
            this.checkChange(childs[key].id)
          }
        } else {
          // 遍历功能、API权限，并同步选择的值
          for (const key in checkedList) {
            if (key.indexOf('_') > 0 && key.split('_')[0] === rowId) {
              checkedList[key] = checkedList[rowId + '']
            }
          }
        }
      }
    },
    getPermissionList() {
      this.listLoading = true
      getAllPermissions().then((response) => {
        // 菜单
        const list = response
        const menus = []
        const checkedList = {}
        const indeterminates = {}

        for (const i in list) {
          if (list[i].parentId === 0) {
            // 菜单
            const menu = list[i]
            const childs = list.filter((x) => x.parentId === menu.id)
            menu.childs = childs
            menus.push(menu)

            // 初始化复选框
            checkedList[menu.id + ''] = false
            indeterminates[menu.id + ''] = false
            for (let childIndex = 0; childIndex < childs.length; childIndex++) {
              const childId = childs[childIndex].id
              checkedList[childId + ''] = false
              indeterminates[childId + ''] = false

              // 获取功能/按钮列表
              const elementList = list.filter(
                (x) => x.parentId === childId && x.permissionType === 1
              )
              for (let index = 0; index < elementList.length; index++) {
                checkedList[childId + '_1_' + elementList[index].id] = false
              }

              // 获取Api列表
              const apiList = list.filter(
                (x) => x.parentId === childId && x.permissionType === 2
              )
              for (let index = 0; index < apiList.length; index++) {
                checkedList[childId + '_2_' + apiList[index].id] = false
              }
            }
          }
        }
        this.checkedList = checkedList
        this.indeterminates = indeterminates

        // 表格
        let tableMenus = []
        for (let i = 0; i < menus.length; i++) {
          tableMenus.push(menus[i])
          tableMenus = tableMenus.concat(menus[i].childs)
        }
        this.tableMenus = tableMenus
        this.list = response

        this.listLoading = false
      })
    },
    getRoleList() {
      this.listLoading = true
      getAllRoleList().then((response) => {
        this.roles = response
        if (this.roles.length > 0) {
          this.roleSelect(0)
        }
        this.listLoading = false
      })
    },
    getRolePermissions(id) {
      this.listLoading = true
      // 获取某个角色包含的权限列表
      getPermissions(id).then((response) => {
        const permissions = response
        const checkedList = this.checkedList
        for (var i in checkedList) {
          checkedList[i] = false
        }
        for (var j in permissions) {
          const item = permissions[j]
          if (item.parentId === 0 || item.permissionType === 0) {
            checkedList[item.id + ''] = true
          } else if (item.permissionType === 1) {
            checkedList[item.parentId + '_1_' + item.id] = true
          } else if (item.permissionType === 2) {
            checkedList[item.parentId + '_2_' + item.id] = true
          }
        }

        this.listLoading = false
      })
    },
    roleSelect(index) {
      this.rootId = this.roles[index].id
      this.getRolePermissions(this.rootId)
    },
    savePermissions() {
      const checkedList = this.checkedList
      const permissionIds = []
      for (const i in checkedList) {
        if (checkedList[i]) {
          if (i.indexOf('_') > 0) {
            permissionIds.push(i.split('_')[2])
          } else {
            permissionIds.push(parseInt(i.split('_')[0]))
          }
        }
      }
      savePermissions(this.rootId, permissionIds).then((response) => {
        if (!response) {
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
        } else {
          this.$notify({
            title: '失败',
            message: '更新失败',
            type: 'info',
            duration: 2000
          })
        }
      })
    }
  }
}
</script>
